# —*— coding: utf-8 -*-

import py_global

from time import sleep
# pip install anyio
from anyio import to_thread, from_thread

import anyio

import logging

logger = logging.getLogger(__name__)


def test_anyio():
    pass


def sync_sleep(task_name):
    logger.info(f'{task_name} start')
    sleep(1)
    logger.info(f'{task_name} sleep 1s')
    sleep(1)
    logger.info(f'{task_name} end')
    return f'{task_name} execute success'


async def main():
    # 容量限制
    limiter = anyio.CapacityLimiter(2)

    async def run_task(task_name, results):
        async with limiter:
            result = await to_thread.run_sync(sync_sleep, task_name)
            results.append(result)

    results = list()
    async with anyio.create_task_group() as task_group:
        for i in range(5):
            task_group.start_soon(run_task, f'task_name_{i}', results)

    logger.info(f"all tasks finished:{results}")


if __name__ == '__main__':
    anyio.run(main)
    pass
